﻿using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using SW.DDD.Application;

namespace LoveShare.Interface.WebApi.Workers
{
    /// <summary>
    /// 后台任务队列
    /// </summary>
    public class BackgroundCommandQueue : IBackgroundCommandQueue
    {
        private ConcurrentQueue<ICommand> _commandQuene = new ConcurrentQueue<ICommand>();
        private SemaphoreSlim _signal = new SemaphoreSlim(0);

        public void QueneCommand(ICommand command)
        {
            _commandQuene.Enqueue(command);
            _signal.Release();
        }

        public async Task<ICommand?> DequeueAsync(CancellationToken cancellationToken)
        {
            await _signal.WaitAsync(cancellationToken);
            _commandQuene.TryDequeue(out var command);
            return command;
        }
    }
}
